const { IS_MISSING_REQUIRED_PARAMETER } = require("../config/error-constants");
const handleIsMissingRequiredParams = (params, requiredParamsStringArr, ctx) => {
    const paramsToStringArr = Object.keys(params);
    const isMissingRequiredParameter =
        paramsToStringArr.length !== requiredParamsStringArr.length ||
        requiredParamsStringArr.some((item) => !paramsToStringArr.includes(item));
    if (isMissingRequiredParameter) {
        ctx.app.emit("error", IS_MISSING_REQUIRED_PARAMETER, ctx);
        return false;
    }

    return true;
};

/**
 * @description 检验必传参数
 * @param {*} modeWithParams
 * @returns
 */
const verifyRequiredParams = (modeWithParams = { mode: "json", requiredParamsStringArr: [] }) => {
    return async (ctx, next) => {
        // 各种请求参数
        //  post => json/urlencoded
        const params = ctx.request.body;
        //  get => queryString
        const queryParams = ctx.query;
        // 各种方法 => parameter
        const parameter = ctx.params;

        let executable = true;
        const { mode, requiredParamsStringArr } = modeWithParams;
        switch (mode) {
            case "json":
            case "urlencoded":
                executable = handleIsMissingRequiredParams(params, requiredParamsStringArr, ctx);
                break;
            case "queryString":
                executable = handleIsMissingRequiredParams(queryParams, requiredParamsStringArr, ctx);
                break;
            case "parameter":
                executable = handleIsMissingRequiredParams(parameter, requiredParamsStringArr, ctx);
                break;
            default:
                break;
        }

        executable && (await next());
    };
};

module.exports = verifyRequiredParams;
